//
//  main.c
//  C_11网络与套接字
//
//  Created by Robin on 16/3/21.
//  Copyright © 2016年 cnbm. All rights reserved.
//

#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <netdb.h>
/**
 BLAB (绑定,监听,接受,开始通信)
 */

void error (char *msg){
    printf("%s : %s\n",msg,strerror(errno));
    exit(1);
}

int open_socket (char *host,char *port){
    
    struct addrinfo *res;
    struct addrinfo hits;
    
    memset(&hits, 0, sizeof(hits));
    hits.ai_family = PF_UNSPEC;
    hits.ai_socktype = SOCK_STREAM;
    if (getaddrinfo(host, port, &hits, &res) == -1) {
        error("Cannot resolve the address");
    }
    
    int d_sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    if (d_sock == -1) {
        error("Con't open socket");
    }
    
    int c = connect(d_sock, res->ai_addr, res->ai_addrlen);
    
    if (c == -1) {
        error("Con't connect the to socket\n");
    }
    
    return d_sock;
}

ssize_t say (int socket,char *msg){
    // darwin
    ssize_t result = send(socket, msg, strlen(msg), 0);
    if (result == -1) {
        fprintf(stderr, "Error talking to the server with %s\n",strerror(errno));
    }
    
    return result;
}

int main(int argc, const char * argv[]) {
    
    int d_sock;
    char buf[255];
    
    d_sock = open_socket("en.wikipedia.org", "80");
    
    sprintf(buf, "GET /wiki/%s http/1.1\r\n",argv[1]);
    
    say(d_sock, buf);
    say(d_sock, "Host: en.wikipedia.rog\r\n\r\n");
    
    char rec[256];
    ssize_t bytesRecvd = recv(d_sock, rec, 255, 0);
    
    while (bytesRecvd) {
        if (bytesRecvd == -1) {
            error("Con't read from server");
        }
        
        rec[bytesRecvd] = '\0';
        printf("%s",rec);
    
        
        bytesRecvd = recv(d_sock, rec, 255, 0);
        
    }
    
    close(d_sock);
    return 0;
}
